package com.jn.zhinongbao.adapter.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.supportingagriculturaltreasures.MerchantOrderActivity;
import com.example.supportingagriculturaltreasures.MyProductsActivity;
import com.example.supportingagriculturaltreasures.R;
import com.example.supportingagriculturaltreasures.adapter.ProductAdapter;
import com.example.supportingagriculturaltreasures.bean.Product;
import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;

import java.util.ArrayList;
import java.util.List;

public class MerchantHomeFragment extends Fragment {


    private ProductAdapter adapter;
    private TextView tvTodaySales, tvMonthSales, tvTotalSales;
    private LinearLayout llMyProducts, llOrderManagement;
    private PreferenceManager preferenceManager;
    private DatabaseHelper databaseHelper;
    private User currentUser;

    public static MerchantHomeFragment newInstance() {
        return new MerchantHomeFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_merchant_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        initViews(view);
        initData();

        setupClickListeners();
        loadUserData();
        loadProductData();
    }

    private void initViews(View view) {

        tvTodaySales = view.findViewById(R.id.tv_today_sales);
        tvMonthSales = view.findViewById(R.id.tv_month_sales);
        tvTotalSales = view.findViewById(R.id.tv_total_sales);
        llMyProducts = view.findViewById(R.id.ll_my_products);
        llOrderManagement = view.findViewById(R.id.ll_order_management);
    }

    private void initData() {
        preferenceManager = new PreferenceManager(getContext());
        databaseHelper = new DatabaseHelper(getContext());
    }



    private void setupClickListeners() {
        llMyProducts.setOnClickListener(v -> {
            // 跳转到我的货品页面
            Intent intent = new Intent(getContext(), MyProductsActivity.class);
            startActivity(intent);
        });

        llOrderManagement.setOnClickListener(v -> {
            // 跳转到商家订单管理页面
            Intent intent = new Intent(getContext(), MerchantOrderActivity.class);
            startActivity(intent);
        });

        // 长按销售数据区域刷新数据
        if (tvTodaySales != null) {
            tvTodaySales.setOnLongClickListener(v -> {
                refreshSalesData();
                return true;
            });
        }
        if (tvMonthSales != null) {
            tvMonthSales.setOnLongClickListener(v -> {
                refreshSalesData();
                return true;
            });
        }
        if (tvTotalSales != null) {
            tvTotalSales.setOnLongClickListener(v -> {
                refreshSalesData();
                return true;
            });
        }
    }

    private void refreshSalesData() {
        loadSalesData();
        Toast.makeText(getContext(), "销售数据已刷新", Toast.LENGTH_SHORT).show();
    }

    private void loadUserData() {
        int userId = preferenceManager.getCurrentUserId();
        if (userId != -1) {
            currentUser = databaseHelper.getUserById(userId);
            if (currentUser != null) {
                // 加载销售数据
                loadSalesData();
            }
        }
    }

    private void loadSalesData() {
        if (currentUser != null) {
            // 从数据库加载真实的销售数据
            double todaySales = databaseHelper.getTodaySales(currentUser.getId());
            double monthSales = databaseHelper.getMonthSales(currentUser.getId());
            double totalSales = databaseHelper.getTotalSales(currentUser.getId());
            
            tvTodaySales.setText(String.format("%.2f", todaySales));
            tvMonthSales.setText(String.format("%.2f", monthSales));
            tvTotalSales.setText(String.format("%.2f", totalSales));
        } else {
            // 如果用户信息为空，显示0
            tvTodaySales.setText("0.00");
            tvMonthSales.setText("0.00");
            tvTotalSales.setText("0.00");
        }
    }

    private void loadProductData() {
        if (currentUser != null) {
            // 从数据库加载真实的商品数据
            List<Product> products = databaseHelper.getProductsByMerchantId(currentUser.getId());
            if (products.isEmpty()) {
                // 如果没有商品，显示示例数据
                products = generateSampleData();
            }
            adapter = new ProductAdapter(products);

        }
    }

    private List<Product> generateSampleData() {
        List<Product> products = new ArrayList<>();
        
        products.add(new Product("我发布的番茄", 15.0, 234, "", "北京市"));
        products.add(new Product("有机黄瓜", 8.0, 156, "", "上海市"));
        products.add(new Product("新鲜生菜", 6.0, 89, "", "广州市"));
        products.add(new Product("农家土豆", 4.0, 345, "", "深圳市"));
        products.add(new Product("绿色菠菜", 7.0, 123, "", "杭州市"));
        
        return products;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 页面重新显示时刷新销售数据
        if (currentUser != null) {
            loadSalesData();
        }
    }
} 